#include <QApplication> // 使用 QApplication 以支持 Qt Charts
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QDebug>
#include "services/DatabaseService.h"
#include "utils/Config.h"
#include "utils/Logger.h"

// Controllers
#include "controllers/ModbusController.h"
#include "controllers/DataController.h"
#include "controllers/AlarmController.h"
#include "controllers/SettingsController.h"

// Models
#include "models/DeviceModel.h"
#include "models/DataRecordModel.h"
#include "models/HistoryModel.h"
#include "models/AlarmModel.h"

// Entities (需要注册到 QML)
#include "entities/Device.h"
#include "entities/DataPoint.h"
#include "entities/AlarmRecord.h"

int main(int argc, char *argv[])
{
    // 设置应用程序属性
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QApplication app(argc, argv); // 使用 QApplication 以支持 Qt Charts

    // 注册 C++ 类型到 QML（让 QML 能够识别这些类型）
    qRegisterMetaType<Device>("Device");
    qRegisterMetaType<DataPoint>("DataPoint");
    qRegisterMetaType<AlarmRecord>("AlarmRecord");

    // 设置应用程序信息
    app.setOrganizationName("IndustrialMonitor");
    app.setOrganizationDomain("modbus.monitor");
    app.setApplicationName("Modbus TCP Monitor");
    app.setApplicationVersion("1.0.0");

    qInfo() << "==============================================";
    qInfo() << "工业设备监控系统 - Modbus TCP 上位机";
    qInfo() << "版本: 1.0.0";
    qInfo() << "==============================================";

    // 初始化数据库服务（单例模式）
    DatabaseService *dbService = DatabaseService::instance();
    if (!dbService->initialize())
    {
        qCritical() << "❌ 数据库初始化失败，程序退出";
        return -1;
    }

    // 初始化日志系统
    Logger *logger = Logger::instance();
    if (!logger->initialize("logs/application.log"))
    {
        qWarning() << "⚠️ 日志系统初始化失败";
    }

    // 初始化配置管理器
    Config *config = Config::instance();
    if (!config->initialize())
    {
        qCritical() << "❌ 配置管理器初始化失败";
        return -1;
    }

    // 记录系统启动日志
    logger->logOperation("system_start", "Application", "系统启动", "admin");

    qInfo() << "\n🎯 正在初始化 Controller 和 Model...";

    // ========================================
    // 创建 Model 实例
    // ========================================
    DeviceModel *deviceModel = new DeviceModel(&app);
    DataRecordModel *dataRecordModel = new DataRecordModel(&app);
    HistoryModel *historyModel = new HistoryModel(&app);
    AlarmModel *alarmModel = new AlarmModel(&app);

    // 加载设备数据
    if (deviceModel->loadFromDatabase())
    {
        qInfo() << "  ✓ 设备数据加载成功，共" << deviceModel->count() << "个设备";
    }
    else
    {
        qWarning() << "  ⚠️ 设备数据加载失败";
    }

    // ========================================
    // 创建 Controller 实例
    // ========================================
    ModbusController *modbusController = new ModbusController(&app);
    DataController *dataController = new DataController(&app);
    AlarmController *alarmController = new AlarmController(&app);
    SettingsController *settingsController = new SettingsController(&app);

    // 关联 Model 到 Controller
    modbusController->setDeviceModel(deviceModel);
    modbusController->setDataRecordModel(dataRecordModel);
    dataController->setDataRecordModel(dataRecordModel);
    dataController->setHistoryModel(historyModel);
    alarmController->setAlarmModel(alarmModel);
    alarmController->setDataRecordModel(dataRecordModel);
    alarmController->setConfig(config);
    settingsController->setConfig(config);
    settingsController->setLogger(logger);
    settingsController->setDatabaseService(dbService);

    qInfo() << "  ✓ Controller 和 Model 初始化完成";

    // ========================================
    // 创建 QML 引擎
    // ========================================
    QQmlApplicationEngine engine;

    // 注册 Controller 到 QML Context
    engine.rootContext()->setContextProperty("modbusController", modbusController);
    engine.rootContext()->setContextProperty("dataController", dataController);
    engine.rootContext()->setContextProperty("alarmController", alarmController);
    engine.rootContext()->setContextProperty("settingsController", settingsController);

    // 注册 Model 到 QML Context
    engine.rootContext()->setContextProperty("deviceModel", deviceModel);
    engine.rootContext()->setContextProperty("dataRecordModel", dataRecordModel);
    engine.rootContext()->setContextProperty("historyModel", historyModel);
    engine.rootContext()->setContextProperty("alarmModel", alarmModel);

    // 注册工具类到 QML Context（可选，用于调试）
    engine.rootContext()->setContextProperty("dbService", dbService);
    engine.rootContext()->setContextProperty("config", config);
    engine.rootContext()->setContextProperty("logger", logger);

    qInfo() << "  ✓ Controller 和 Model 已注册到 QML Context";

    // 加载 QML 主界面
    const QUrl url(QStringLiteral("qrc:/qml/Main.qml"));

    QObject::connect(
        &engine, &QQmlApplicationEngine::objectCreated,
        &app, [url](QObject *obj, const QUrl &objUrl)
        {
            if (!obj && url == objUrl) {
                qCritical() << "❌ QML 主界面加载失败";
                QCoreApplication::exit(-1);
            } },
        Qt::QueuedConnection);

    engine.load(url);

    if (!engine.rootObjects().isEmpty())
    {
        qInfo() << "✅ QML 界面加载成功";
    }

    qInfo() << "==============================================";
    qInfo() << "系统启动完成，等待用户操作...";
    qInfo() << "==============================================";

    return app.exec();
}
